//
//  LocationDecoder.m
//  XMJJ_zml
//
//  Created by 杨何华 on 2025/5/27.
//

#import "LocationDecoder.h"

@implementation LocationDecoder
+ (instancetype)sharedDecoder {
    static LocationDecoder *sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[self alloc] init];
    });
    return sharedInstance;
}

- (instancetype)init {
    self = [super init];
    if (self) {
        _locationManager = [[CLLocationManager alloc] init];
        _locationManager.delegate = self;
        _locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        
        _geocoder = [[CLGeocoder alloc] init];
    }
    return self;
}

- (void)reverseGeocodeLocation:(CLLocation *)location
                    completion:(void(^)(NSDictionary *addressInfo, NSError *error))completion {
    self.completionHandler = completion;
    
    [self.geocoder reverseGeocodeLocation:location completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
        if (error) {
            if (self.completionHandler) {
                self.completionHandler(nil, error);
            }
            return;
        }
        
        CLPlacemark *placemark = [placemarks firstObject];
        if (placemark) {
            NSDictionary *addressInfo = [self addressDictionaryFromPlacemark:placemark];
            if (self.completionHandler) {
                self.completionHandler(addressInfo, nil);
            }
        } else {
            if (self.completionHandler) {
                NSError *noPlacemarkError = [NSError errorWithDomain:@"LocationDecoder" code:1003 userInfo:@{NSLocalizedDescriptionKey: @"无法获取地址信息"}];
                self.completionHandler(nil, noPlacemarkError);
            }
        }
    }];
}

- (void)getCurrentLocationWithCompletion:(void(^)(NSDictionary *addressInfo, NSError *error))completion {
    self.completionHandler = completion;
    
    if ([CLLocationManager locationServicesEnabled]) {
        CLAuthorizationStatus status;
        if (@available(iOS 14.0, *)) {
            status = self.locationManager.authorizationStatus;
        } else {
            status = [CLLocationManager authorizationStatus];
        }
        
        switch (status) {
            case kCLAuthorizationStatusAuthorizedWhenInUse:
            case kCLAuthorizationStatusAuthorizedAlways:
                [self.locationManager startUpdatingLocation];
                break;
                
            case kCLAuthorizationStatusNotDetermined:
                [self.locationManager requestWhenInUseAuthorization];
                break;
                
            default:
                if (self.completionHandler) {
                    NSError *permissionError = [NSError errorWithDomain:@"LocationDecoder" code:1001 userInfo:@{NSLocalizedDescriptionKey: @"定位权限不足"}];
                    self.completionHandler(nil, permissionError);
                }
                break;
        }
    } else {
        if (self.completionHandler) {
            NSError *serviceError = [NSError errorWithDomain:@"LocationDecoder" code:1002 userInfo:@{NSLocalizedDescriptionKey: @"定位服务未启用"}];
            self.completionHandler(nil, serviceError);
        }
    }
}

- (NSDictionary *)addressDictionaryFromPlacemark:(CLPlacemark *)placemark {
    return @{
        @"country": placemark.country ?: @"",                   // 国家
        @"province": placemark.administrativeArea ?: @"",       // 省份
        @"city": placemark.locality ?: @"",                     // 城市
        @"district": placemark.subLocality ?: @"",              // 区县
        @"street": placemark.thoroughfare ?: @"",               // 街道
        @"streetNumber": placemark.subThoroughfare ?: @"",      // 门牌号
        @"postalCode": placemark.postalCode ?: @"",             // 邮编
        @"name": placemark.name ?: @"",                         // 地址名称
        @"location": [NSString stringWithFormat:@"%f,%f", placemark.location.coordinate.latitude, placemark.location.coordinate.longitude] // 经纬度
    };
}

#pragma mark - CLLocationManagerDelegate

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations {
    CLLocation *currentLocation = [locations lastObject];
    [manager stopUpdatingLocation];
    
    [self reverseGeocodeLocation:currentLocation completion:self.completionHandler];
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error {
    [manager stopUpdatingLocation];
    
    if (self.completionHandler) {
        self.completionHandler(nil, error);
    }
}

- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status {
    switch (status) {
        case kCLAuthorizationStatusAuthorizedWhenInUse:
        case kCLAuthorizationStatusAuthorizedAlways:
            [self.locationManager startUpdatingLocation];
            break;
            
        default:
            if (self.completionHandler) {
                NSError *permissionError = [NSError errorWithDomain:@"LocationDecoder" code:1001 userInfo:@{NSLocalizedDescriptionKey: @"定位权限不足"}];
                self.completionHandler(nil, permissionError);
            }
            break;
    }
}

@end
